package com.mes.datasource.controller;

import com.mes.datasource.service.DataSourceService;
import com.mes.datasource.util.CheckSQLParamsUtil;
import com.mes.datasource.vo.DataSourceParamVO;
import com.mes.datasource.vo.DataSourceVO;
import com.mes.entity.User;
import com.yy.base.common.action.BaseCtrl;
import com.yy.base.page.Message;
import com.yy.base.page.Page;
import com.yy.base.util.SessionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("ds")
public class DataSourceController extends BaseCtrl {
	@Autowired
	private DataSourceService dataSourceService;

	//加载工序信息
	@ResponseBody
	@RequestMapping(value="/*",method=RequestMethod.POST)
	public Message initProcessInfo(HttpServletRequest request){
		Message msg = new Message();
		String orgId = (String)request.getSession().getAttribute("orgId");
		User user = this.getLoginUser(request);
		String url = request.getRequestURI();

		DataSourceVO data = dataSourceService.getRequestData(url);
		if (data == null) {
			msg.setErrorMessage("未找到路径“" + url + "”对应的数据源配置！");
			return msg;
		}
		Map<String, Object> params = new HashMap();
		if (data.getParams() != null && !data.getParams().isEmpty()) {
			Object value = null;
			for (DataSourceParamVO param : data.getParams()) {
				value = request.getParameter(param.getParamName());
				if (value != null) {
					params.put(param.getParamName(), value);
				} else if (param.getDefaultValue() != null) {
					if ("userId".equalsIgnoreCase(param.getParamName())) {
						value = user.getId();
					} else if ("userOrg".equalsIgnoreCase(param.getParamName())) {
						value = orgId;
					} else {
						value = param.getDefaultValue();
					}
					params.put(param.getParamName(), value);
				} else if (param.isMust()) {
					msg.setErrorMessage(param.getName() + "不能为空!");
					return msg;
				}
			}
		}

		CheckSQLParamsUtil util = new CheckSQLParamsUtil(data.getSql(), params, "1=1");

		if (data.getRowSize() != null && data.getRowSize() > 0) {
			if (data.getRowSize() == 1) {
				msg.setData("data", dataSourceService.queryUnique(util.getSql(), util.getParamValues()));
			} else {
				Page page = SessionInfo.getPage();
				page.setTotal(data.getRowSize());
				List<Map<String, Object>> list = dataSourceService.splitQuery(util.getSql(), util.getParamValues());
				msg.setSplitPageList(list);
			}
		} else {
			List<Map<String, Object>> list = dataSourceService.queryList(util.getSql(), util.getParamValues());
			msg.setSplitPageList(list);
		}
		return msg;
	}
}
